package com.mediacloud.app.newsmodule.fragment.album;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.mediacloud.app.appfactory.cache.AppConfig;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.AlbumListData;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.album.vod.VodAlbumNewsListItemAdapter;
import com.mediacloud.app.newsmodule.fragment.BaseExpandListFragment;
import com.mediacloud.app.newsmodule.utils.AlbumListDataInvoker;
import com.mediacloud.app.newsmodule.utils.CacheDataKt;
import com.mediacloud.app.newsmodule.utils.LBSRefreshLocation;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.reslib.enums.Navigate;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import org.json.JSONObject;

/**
 * 點播专辑列表
 *
 * @author x
 */
public class VodAlbumListFragment extends BaseExpandListFragment<VodAlbumNewsListItemAdapter, List<String>, Map<String, List<CatalogItem>>, String, CatalogItem> {
    protected String catalogID;
    protected Bundle arguments = null;
    protected CatalogItem catalogItem;
    protected AlbumListDataInvoker dataInvoker;
    protected BaseDataInvokeCallBack dataCallback;
    public static final String HAVE_BANNER = "1";

    public void CatalogListContentPagerFragment() {
    }

    protected void initDataInvoker() {
        dataCallback = new BaseAlbumListDataInvokeCallBack();
        dataInvoker = new AlbumListDataInvoker(dataCallback);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            arguments = savedInstanceState.getBundle(SaveArgs);
        }
        childGropData = new LinkedHashMap<String, List<CatalogItem>>();
        groupLabel = new ArrayList<String>();
        initDataInvoker();
    }

    @Override
    public void initView() {
        attached = false;
        isLoading = false;
        pageNum = 1;
        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        loadingView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showStateView(TYPE_LOADING, false);
                onRefresh();
            }
        });
        mCatalogContentItemListView = findViewById(R.id.mCatalogContentItemListView);
        mCatalogContentItemListView.setOnGroupClickListener(new OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                return true;
            }
        });
        mCatalogContentItemListView.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                CatalogItem item = adaptor.getChild(groupPosition, childPosition);
                if (item != null) {
                    //todo 校验item的参数是否过大
                    NewsItemClickUtils.OpenItemNewsHandle(getActivity(), item.getCatalogStyle(), item, catalogItem);
                }
                return false;
            }
        });
        mEmptyContent = findViewById(R.id.mEmptyContent);
        adaptor = new VodAlbumNewsListItemAdapter(getActivity());
        adaptor.setBaseExpandableListParents(groupLabel);
        adaptor.setBaseExpandableLisChilds(childGropData);
        if (getFragmentArguments() != null) {
            arguments = getFragmentArguments();
            catalogID = arguments.getString("id");
            catalogItem = arguments.getParcelable("catalog");
        } else if (arguments != null) {
            catalogID = arguments.getString("id");
            catalogItem = arguments.getParcelable("catalog");
        }
        adaptor.catalogItem = catalogItem;
        addLBSChosoeHeader(catalogItem);
        mCatalogContentItemListView.addHeaderView(headerViewContainer);
        componetContainer.componentListItemStyleAdaptor.catalogItem = catalogItem;
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        mCatalogContentItemListView.setAdapter(adaptor);
        mEmptyContent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showStateView(TYPE_LOADING, false);
                onRefresh();
            }
        });
        setRefreshLayoutColor(refreshLayout,getNavigate());
    }
    @org.jetbrains.annotations.Nullable
    @Override
    public Navigate getNavigate()
    {
        if(catalogItem!= null&&catalogItem.getNavigate()!=null)
            return catalogItem.getNavigate();
        return super.getNavigate();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dataInvoker != null) {
            dataInvoker.destory();
            dataInvoker = null;
        }
        attached = false;
        if (componetContainer != null)
            componetContainer.dispose();
        componetContainer = null;
    }

/*    @Override
    public void onResume() {
        if (emptyTipsText == null) {
            emptyTipsText = Utility.findViewById(mRootView, R.id.emptyTipsText);
        }
        super.onResume();
        if (!attached) {
            attached = true;
            //onRefresh();
            userCache();
        }
    }*/

    @Override
    public int getLayoutResID() {
        return R.layout.fragment_ablum_list;
    }

    @Override
    public void onRefresh() {
        AppConfig appConfig=new AppConfig(getActivity());
        boolean unkeep=appConfig.lbsIsAutoMode()&& Utility.gpsIsOpen(getActivity());

        if (catalogItem != null && catalogItem.getLbsItem() != null && !isFirst && unkeep)
        {
            new LBSRefreshLocation(this).start(getActivity());
        } else {
            isFirst = false;
            doRefresh();
        }
    }

    boolean isFirst = true;
    @Override
    public final void doRefresh() {
        super.doRefresh();
        if (isLoading)
            return;
        isLoading = true;
        pageNum = 1;
        if (mCatalogContentItemListView != null) {
            Log.w("APPTAG", "onFresh");
            getNewsListData();
        }
    }

    @Override
    public void useCache() {
        if(mCatalogContentItemListView!=null){
            AlbumListData dataResult = CacheDataKt.readData(this, catalogID, AlbumListData.class);
            if (adaptor != null && adaptor.getBaseExpandableLisChilds() != null && adaptor.getBaseExpandableLisChilds().size() == 0 && dataCallback != null && dataResult != null) {
                Log.w("APPTAG", "useCache");
                dataCallback.success(dataResult);
            }else{
                onRefresh();
            }
        }

    }

    /**
     * 取新闻列表
     */
    protected void getNewsListData() {
        dataInvoker.getArticleListById(catalogID/*, UserInfo.getUserInfo(getActivity()).getUserid()*/, pageNum, 100);
    }

    @Override
    public void onLoadMore() {
        if (isLoading)
            return;
        isLoading = true;
        pageNum++;
        getNewsListData();
    }

    public class BaseAlbumListDataInvokeCallBack extends BaseDataInvokeCallBack<AlbumListData> {
        @Override
        public void success(AlbumListData result) {
            if (adaptor == null)
                return;
            isLoading = false;
            if (pageNum == 1)
                CacheDataKt.saveData(VodAlbumListFragment.this, catalogID, result.orginData + "");
            boolean more=result.currentPage < result.lastPage;
            if(more)
                refreshLayout.finishLoadMore();
            else
                refreshLayout.finishLoadMoreWithNoMoreData();
            JSONObject data = result.orginData.optJSONObject("data");
            if(pageNum==1){
                if (FloatButtonGroup.haveFloatField(data)) {
                    initFloatWin(data);
                } else {
                    hideFloatWin();
                }
            }
            if (pageNum == 1) {
                refreshLayout.finishRefresh();
                if (adaptor.getBaseExpandableListParents() != null)
                    adaptor.getBaseExpandableListParents().clear();
                if (adaptor.getBaseExpandableLisChilds() != null)
                    adaptor.getBaseExpandableLisChilds().clear();
                //添加组件  用的HeadView
                componetContainer.updateComponent(result.componentItems);
            }
            childGropData.clear();
            groupLabel.clear();
            adaptor.groupOpend = result.isOpenedGroup();
            String label = null;
            // 直接覆盖之前的 根据标签设置分组没和分组数据来判断分组标签的显示
//			if(result.videoList.size()>0)
            {
                label = getResources().getString(R.string.vodalbum_video);
                groupLabel.add(label);
                childGropData.put(label, result.videoList);
            }
//			if(result.audioList.size()>0)
            {
                label = getResources().getString(R.string.vodalbum_audio);
                groupLabel.add(label);
                childGropData.put(label, result.audioList);
            }
            adaptor.setBaseExpandableListParents(groupLabel);
            adaptor.setBaseExpandableLisChilds(childGropData);
            adaptor.notifyDataSetChanged();
            closeStateView();
            if (childGropData.size() == 0) {
                showStateView(TYPE_NO_CONTENT, false);
            }
            for (int i = 0; i < adaptor.getGroupCount(); i++) {
                if (adaptor.getChildrenCount(i) > 0)
                    mCatalogContentItemListView.expandGroup(i);
            }
        }
    }

    public abstract class BaseDataInvokeCallBack<T> implements DataInvokeCallBack<T> {
        @Override
        public void fault(Object object) {
            isLoading = false;
            pageNum--;
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            if (adaptor != null && (adaptor.getBaseExpandableLisChilds() == null
                    || adaptor.getBaseExpandableLisChilds().size() == 0)) {
                if (object == null) {
                    showStateView(TYPE_NO_CONTENT, false);
                } else {
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
                }
            } else {
                closeStateView();
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("id", catalogID);
        outState.putParcelable("catalog", catalogItem);
        super.onSaveInstanceState(outState);
    }

}